from ui.borrowmanager import *
from service import *
from addBook import *
from PyQt5.QtWidgets import QHeaderView
from PyQt5.QtGui import  QStandardItemModel,QStandardItem

class BorrowManagerMainWindow(Ui_BorrowManagerMainWindow, QtWidgets.QMainWindow):
    def __init__(self, ) -> None:
        super().__init__()
        self.setupUi(self)
        self.queryBorrow()
        self.pushButton.clicked.connect(self.queryBorrow)
        self.pushButton_2.clicked.connect(self.returnBook)

    def returnBook(self):
        selected_rows = self.tableView.selectionModel().selectedRows()
        if selected_rows:
            for index in selected_rows:
                # 获取行号
                row = index.row()
                # 获取模型
                model = index.model()
                # 提取该行所有列的内容
                row_data = [model.data(model.index(row, col)) for col in range(model.columnCount())]
                print(f"选中行 {row} 的内容: {row_data}")
                user_id = row_data[-2]
                book_id = row_data[-1]
                borrowsvc = BorrowService()
                borrowsvc.returnBook(user_id,book_id)
        else:
            print("没有选中任何行")

    def queryBorrow(self):
        borsvc = BorrowService()
        bor_list = borsvc.all()
        
        us = UserService()
        bs = BookService()

        self.model=QStandardItemModel(6,6)#存储任意结构数据
        self.model.setHorizontalHeaderLabels(['借阅人','书名','借阅时间','还书时间','借阅人id','图书id'])
        row = 0
        for u in bor_list:
            print(u.user_id, u.book_id)
            column = 0
            user = us.getUserById(u.user_id)
            b = bs.getBookById(u.book_id)
            self.model.setItem(row,column,QStandardItem("%s"%(user.username)))
            self.model.setItem(row,column+1,QStandardItem("%s"%(b.title)))
            self.model.setItem(row,column+2,QStandardItem("%s"%(u.borrow_time)))
            self.model.setItem(row,column+3,QStandardItem("%s"%(u.return_time)))
            self.model.setItem(row,column+4,QStandardItem("%s"%(u.user_id)))
            self.model.setItem(row,column+5,QStandardItem("%s"%(u.book_id)))
            row += 1
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
